﻿using System;
using System.Text;
using System.Ext.Xml;
using System.Xml;
using System.Reflection;

namespace mfXmlSerializer
{
    /// <summary>
    /// represents the serialization strategy for datetime
    /// </summary>
    public class mfMapDateTimeElement : mfMapBaseElement
    {
        #region Consts

        /// <summary>
        /// default dateformat 
        /// </summary>
        private const string C_STR_DATETIMEFORMAT = "yyyy-MM-ddTHH:mm:ss";

        #endregion

        #region CTOR

        public mfMapDateTimeElement(mfMapBaseElement baseElement)
            : base(baseElement.Name, baseElement.SetMethod, baseElement.GetMethod, baseElement.ChildMap)
        { }

        #endregion

        #region Methods

        protected override void SerializeElement(XmlWriter xmlWriter, object source)
        {
            //get ToString(formatProvider) method on DateTime Object ('dt.ToString("yyyy-MM-ddTHH:mm:ss+HH:mm');)
            var dateTimeToStringMethod = ElementType.GetMethod("ToString", new Type[] { typeof(String) });
            //get DateTime object from target
            var dateTimeValue = GetMethod.Invoke(source, null);

            var dateTimeValueString = dateTimeToStringMethod.Invoke(dateTimeValue, new string[] { C_STR_DATETIMEFORMAT });
            xmlWriter.WriteElementStringIfNotNull(Name, dateTimeValueString.ToString());
        }

        protected override void DeserializeElement(XmlReader xmlReader, object target)
        {
            xmlReader.Read();
            if (xmlReader.IsNotNodeTextType(this)) return;
            //convert string to DateTime object
            var dtValue = xmlReader.Value.ConvertToDateTime();
            SetElement(xmlReader, target, dtValue);
        }

        protected override void ExecuteSetElement(object target, string newValue)
        {
            var dtValue = newValue.ConvertToDateTime();
            SetMethod.Invoke(target, new object[] { dtValue });
        }

        #endregion
    }
}
